package codename.primavera.web.security.util;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * The Class SpringSecurityUtils.
 */
public final class SpringSecurityUtils {

    /** The Constant instance. */
    private static final SpringSecurityUtils INSTANCE;

    static {
        INSTANCE = new SpringSecurityUtils();
    }

    /**
     * Instantiates a new spring security utils.
     */
    private SpringSecurityUtils() {

    }

    /**
     * Gets the single instance of SpringSecurityUtils.
     * @return single instance of SpringSecurityUtils
     */
    public static SpringSecurityUtils getInstance() {
        return INSTANCE;
    }

    /**
     * Checks if the current user has at least one of the given
     * authorities.
     * @param authorities the authorities
     * @return true, if the current user has one of the authorities
     */
    public static boolean userHasAtLeastOneRole(final String... authorities) {
        final Authentication user = SecurityContextHolder.getContext().getAuthentication();
        for (GrantedAuthority grantedAuthority : user.getAuthorities()) {
            for (final String authority : ArrayUtils.nullToEmpty(authorities)) {
                if (authority.equals(grantedAuthority.getAuthority())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Gets the user.
     * @return the user
     */
    public static UserDetails getUser() {
        final Authentication user = SecurityContextHolder.getContext().getAuthentication();
        if (user instanceof AnonymousAuthenticationToken) {
            return null;
        } else {
            return (UserDetails) user.getPrincipal();
        }
    }

}
